package com.xiexie.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xiexie.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Date 2022-04-07 14:46
 * @Author xie
 */
@RestController
@RequestMapping("/order")
public class OrderSentinelController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IOrderService orderService;


    @RequestMapping("sentinel")
    public String sentinel() {
        return "hello sentinel";
    }

    /**
     * 测试流控规则 - QPS
     * @return java.lang.String
     */
    @RequestMapping("flow")
    //@SentinelResource(value = "flow", blockHandler = "blockHandlerFlow")
    public String flow() {

        return "hello flow";
    }

    public String blockHandlerFlow(BlockException e) {
        return "hello flow 进入流控了";
    }

    /**
     * 测试流控规则 - 线程数隔离
     * @return java.lang.String
     */
    @RequestMapping("flowThread")
    @SentinelResource(value = "flowThread", blockHandler = "blockHandlerFlow")
    public String flowThread() throws InterruptedException {
        TimeUnit.SECONDS.sleep(5);
        return "hello flowThread";
    }


    /************************ 测试关联流控 ****************************/
    @RequestMapping("/add")
    public String add() {
        System.out.println("下单成功");
        return "生成订单";
    }

    @RequestMapping("/get")
    public String get() throws InterruptedException {
        return "查询订单";
    }

    /************************ 测试链路流控 ****************************/
    @RequestMapping("/test1")
    public String test1() {
        return orderService.getUser();
    }

    @RequestMapping("/test2")
    public String test2() {
        return orderService.getUser();
    }

    /**
     * warmUp（脉冲流量）
     * @return java.lang.String
     */
    @RequestMapping("/warmUp")
    public String warmUp() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "warmUp";
    }


    /**
     * 慢调用比例
     * @return java.lang.String
     */
    @RequestMapping("/slowRequestRatio")
    public String slowRequestRatio() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "slowRequestRatio";
    }

}
